package com.sl.mes.app.controller;

import com.sl.mes.app.util.HttpUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;


/**
 * API工具类
 */
@RestController
@SuppressWarnings("all")
public class ApiRequestTools {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static String APPID = "APPID";

    public static String MADOMAIN = "http://xhhg.natapp1.cc/dmobile"; //开发环境移动审批

    public ApiRequestTools() {

    }

    /**
     * OA用户认证服务
     *
     * @param usercode
     * @param password
     * @param req
     * @param res
     */
    public static synchronized String exeOaSsoLogin(String usercode) throws Exception {

        String result = "";
        try {
            // 第一步：API服务地址
            String URL = MADOMAIN + "/donorapprove/handler.json";
            HttpPost httpPost = new HttpPost(URL);

            // 第二步：转换POST表单Map并放入请求体
            List<NameValuePair> list = new ArrayList<NameValuePair>();

            list.add(new BasicNameValuePair("params[transtype]", "request_token"));
            list.add(new BasicNameValuePair("params[user_id]", usercode));

            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
                httpPost.setEntity(entity);
            }

            // 第三步：发送http post请求，并得到相应结果
            DefaultHttpClient httpclient = HttpUtil.getHttpClient();

            synchronized (httpclient) {
                HttpResponse response = httpclient.execute(httpPost);

                if (response != null) {
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        result = EntityUtils.toString(resEntity, "UTF-8");
                    }
                } else {
                    HashMap<String, Object> rtMap = new HashMap<String, Object>();
                    rtMap.put("retflag", 1);
                    rtMap.put("resMsg", "信息：你要的数据没有得到");
                    HashMap<String, Object> rMap = new HashMap<String, Object>();

                    rMap.put("result", rtMap);
                    rMap.put("res", 0);
                    rMap.put("resMsg", "信息：你要的数据没有得到");
                    result = map2json(rMap);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            HashMap<String, Object> rtMap = new HashMap<String, Object>();
            rtMap.put("retflag", 1);
            rtMap.put("resMsg", "信息：" + e.getMessage());
            HashMap<String, Object> rMap = new HashMap<String, Object>();

            rMap.put("result", rtMap);
            rMap.put("res", 0);
            rMap.put("resMsg", "信息：" + e.getMessage());
            result = map2json(rMap);
        }
        return result;
    }

    /**
     * 调用登录服务
     *
     * @param usercode
     * @param password
     * @param req
     * @param res
     */
    public static synchronized String exeDmobileLogin(String usercode, String password) throws Exception {
        String result = "";
        try {
            // 第一步：API服务地址
            String URL = MADOMAIN + "/donorapprove/handler.json";
            HttpPost httpPost = new HttpPost(URL);

            // 第二步：转换POST表单Map并放入请求体
            List<NameValuePair> list = new ArrayList<NameValuePair>();

            list.add(new BasicNameValuePair("params[transtype]", "user_auth"));
            list.add(new BasicNameValuePair("params[usercode]", usercode));
            list.add(new BasicNameValuePair("params[password]", password));

            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
                httpPost.setEntity(entity);
            }

            // 第三步：发送http post请求，并得到相应结果
            DefaultHttpClient httpclient = HttpUtil.getHttpClient();

            synchronized (httpclient) {
                HttpResponse response = httpclient.execute(httpPost);

                if (response != null) {
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        result = EntityUtils.toString(resEntity, "UTF-8");
                    }
                } else {
                    HashMap<String, Object> rtMap = new HashMap<String, Object>();
                    rtMap.put("retflag", 1);
                    rtMap.put("resMsg", "信息：你要的数据没有得到");
                    HashMap<String, Object> rMap = new HashMap<String, Object>();

                    rMap.put("result", rtMap);
                    rMap.put("res", 0);
                    rMap.put("resMsg", "信息：你要的数据没有得到");
                    result = map2json(rMap);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            HashMap<String, Object> rtMap = new HashMap<String, Object>();
            rtMap.put("retflag", 1);
            rtMap.put("resMsg", "信息：" + e.getMessage());
            HashMap<String, Object> rMap = new HashMap<String, Object>();

            rMap.put("result", rtMap);
            rMap.put("res", 0);
            rMap.put("resMsg", "信息：" + e.getMessage());
            result = map2json(rMap);
        }
        return result;
    }

    /**
     * 调用移动审批后台服务方法
     *
     * @param req
     * @param res
     * @throws Exception
     */
    public static synchronized void exeDmobileRequest(HttpServletRequest req, HttpServletResponse res,List<NameValuePair> list) throws Exception {
        try {

            // 第一步：API服务地址
            String URL = MADOMAIN + "/donorapprove/handler.json";
            HttpPost httpPost = new HttpPost(URL);

            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
                httpPost.setEntity(entity);
            }

            // 第五步：发送http post请求，并得到相应结果
            DefaultHttpClient httpclient = HttpUtil.getHttpClient();

            synchronized (httpclient) {
                HttpResponse response = httpclient.execute(httpPost);

                if (response != null) {
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        String result = EntityUtils.toString(resEntity, "UTF-8");

                        System.out.println(result);

                        //返回页面
                        res.setHeader("Access-Control-Allow-Origin", "*");
                        res.setCharacterEncoding("UTF-8");
                        req.setCharacterEncoding("UTF-8");
                        res.setContentType("text/html;charset=UTF-8");
                        res.getWriter().write(result);

                    }
                } else {
                    HashMap<String, Object> rtMap = new HashMap<String, Object>();
                    rtMap.put("retflag", 1);
                    rtMap.put("resMsg", "你要的数据没有得到");
                    HashMap<String, Object> rMap = new HashMap<String, Object>();

                    rMap.put("result", rtMap);
                    rMap.put("res", 0);
                    rMap.put("resMsg", "你要的数据没有得到");
                    res.setHeader("Access-Control-Allow-Origin", "*");
                    res.setCharacterEncoding("UTF-8");
                    res.setCharacterEncoding("UTF-8");
                    res.setContentType("text/html;charset=UTF-8");
                    res.getWriter().write(map2json(rMap));
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            HashMap<String, Object> rtMap = new HashMap<String, Object>();
            rtMap.put("retflag", 1);
            rtMap.put("resMsg", "信息：" + e.getMessage());
            HashMap<String, Object> rMap = new HashMap<String, Object>();

            rMap.put("result", rtMap);
            rMap.put("res", 0);
            rMap.put("resMsg", "信息：" + e.getMessage());
            res.setHeader("Access-Control-Allow-Origin", "*");
            res.setCharacterEncoding("UTF-8");
            res.setCharacterEncoding("UTF-8");
            res.setContentType("text/html;charset=UTF-8");
            res.getWriter().write(map2json(rMap));
        }
    }


    /**
     * 解码sun.misc.BASE64Decoder
     *
     * @param str
     * @return
     */
    private static byte[] myBASE64Decode(String str) {
        byte[] bt = null;
        try {
            sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
            bt = decoder.decodeBuffer(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bt;
    }



    /**
     * 将对象转换成JSON字符串,并返回结果
     *
     * @param map
     * @return
     */
    public static String map2json(Map<?, ?> map) {
        StringBuilder json = new StringBuilder();
        json.append("{");
        if (map != null && map.size() > 0) {
            for (Object key : map.keySet()) {
                json.append(object2json(key));
                json.append(":");
                json.append(object2json(map.get(key)));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, '}');
        } else {
            json.append("}");
        }
        return json.toString();
    }


    /**
     * 对象转换成字符串
     *
     * @param obj
     * @return
     */
    public static String object2json(Object obj) {
        StringBuilder json = new StringBuilder();
        if (obj == null) {
            json.append("\"\"");
        } else if (obj instanceof Double || obj instanceof Date || obj instanceof String || obj instanceof Integer || obj instanceof Float || obj instanceof Boolean || obj instanceof Short || obj instanceof Double || obj instanceof Long || obj instanceof BigDecimal || obj instanceof BigInteger
                || obj instanceof Byte) {
            json.append("\"").append(string2json(obj.toString())).append("\"");
        } else if (obj instanceof Object[]) {
            json.append(array2json((Object[]) obj));
        } else if (obj instanceof List) {
            json.append(list2json((List<?>) obj));
        } else if (obj instanceof Map) {
            json.append(map2json((Map<?, ?>) obj));
        } else if (obj instanceof Set) {
            json.append(set2json((Set<?>) obj));
        } else {
            json.append(bean2json(obj));
        }
        return json.toString();
    }

    public static String bean2json(Object bean) {
        StringBuilder json = new StringBuilder();
        json.append("{");
        PropertyDescriptor[] props = null;
        try {
            props = Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors();
        } catch (IntrospectionException e) {
        }
        if (props != null) {
            for (int i = 0; i < props.length; i++) {
                try {
                    String name = object2json(props[i].getName());
                    String value = object2json(props[i].getReadMethod().invoke(bean));
                    json.append(name);
                    json.append(":");
                    json.append(value);
                    json.append(",");
                } catch (Exception e) {
                }
            }
            json.setCharAt(json.length() - 1, '}');
        } else {
            json.append("}");
        }
        return json.toString();
    }


    public static String set2json(Set<?> set) {
        StringBuilder json = new StringBuilder();
        json.append("[");
        if (set != null && set.size() > 0) {
            for (Object obj : set) {
                json.append(object2json(obj));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, ']');
        } else {
            json.append("]");
        }
        return json.toString();
    }

    public static String list2json(List<?> list) {
        StringBuilder json = new StringBuilder();
        json.append("[");
        if (list != null && list.size() > 0) {
            for (Object obj : list) {
                json.append(object2json(obj));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, ']');
        } else {
            json.append("]");
        }
        return json.toString();
    }

    public static String array2json(Object[] array) {
        StringBuilder json = new StringBuilder();
        json.append("[");
        if (array != null && array.length > 0) {
            for (Object obj : array) {
                json.append(object2json(obj));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, ']');
        } else {
            json.append("]");
        }
        return json.toString();
    }

    public static String string2json(String s) {
        if (s == null)
            return "";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            switch (ch) {
                case '"':
                    sb.append("\\\"");
                    break;
                case '\\':
                    sb.append("\\\\");
                    break;
                case '\b':
                    sb.append("\\b");
                    break;
                case '\f':
                    sb.append("\\f");
                    break;
                case '\n':
                    sb.append("\\n");
                    break;
                case '\r':
                    sb.append("\\r");
                    break;
                case '\t':
                    sb.append("\\t");
                    break;
                case '/':
                    sb.append("\\/");
                    break;
                default:
                    if (ch >= '\u0000' && ch <= '\u001F') {
                        String ss = Integer.toHexString(ch);
                        sb.append("\\u");
                        for (int k = 0; k < 4 - ss.length(); k++) {
                            sb.append('0');
                        }
                        sb.append(ss.toUpperCase());
                    } else {
                        sb.append(ch);
                    }
            }
        }
        return sb.toString();
    }

    /**
     * 调用生产订单的查询
     *
     * @param usercode
     * @param password
     * @param req
     * @param res
     */
    public static synchronized String getOid() throws Exception {
        String result = "";
        try {
            // 第一步：API服务地址
            String URL = "http://127.0.0.1:8088/mescloud/mes/puboid/getPubOidById";
            HttpPost httpPost = new HttpPost(URL);

            // 第二步：转换POST表单Map并放入请求体
            List<NameValuePair> list = new ArrayList<NameValuePair>();

            list.add(new BasicNameValuePair("groupcode", "0001"));

            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
                httpPost.setEntity(entity);
            }

            // 第三步：发送http post请求，并得到相应结果
            DefaultHttpClient httpclient = HttpUtil.getHttpClient();

            synchronized (httpclient) {
                HttpResponse response = httpclient.execute(httpPost);

                if (response != null) {
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        result = EntityUtils.toString(resEntity, "UTF-8");
                    }
                } else {
                }
            }
        } catch (Exception e) {
        }
        return result;
    }


    /**
     * 调用生产订单的修改
     *
     * @param usercode
     * @param password
     * @param req
     * @param res
     */
    public static synchronized String updateOid(String groupCode,String oId) throws Exception {
        String result = "";
        try {
            // 第一步：API服务地址
            String URL = "http://127.0.0.1:8088/mescloud/mes/puboid/updataPubOidVoById";
            HttpPost httpPost = new HttpPost(URL);

            // 第二步：转换POST表单Map并放入请求体
            List<NameValuePair> list = new ArrayList<NameValuePair>();

            //TODO:将参数添加到这儿
            list.add(new BasicNameValuePair("groupcode", groupCode));
            list.add(new BasicNameValuePair("puboid", oId));

            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
                httpPost.setEntity(entity);
            }

            // 第三步：发送http post请求，并得到相应结果
            DefaultHttpClient httpclient = HttpUtil.getHttpClient();

            synchronized (httpclient) {
                HttpResponse response = httpclient.execute(httpPost);

                if (response != null) {
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        result = EntityUtils.toString(resEntity, "UTF-8");
                    }
                } else {
                    throw new Exception("更新id异常!");
                }
            }
        } catch (Exception e) {
            throw new Exception("更新id异常!"+e.getMessage());
        }
        return result;
    }


    /**
     * 调用登录服务
     *
     * @param usercode
     * @param password
     * @param req
     * @param res
     */
    public static synchronized String insertOid(String groupCode,String oId) throws Exception {
        String result = "";
        try {
            // 第一步：API服务地址
            String URL = "http://127.0.0.1:8088/mescloud/mes/puboid/insertPubOidVoById";
            HttpPost httpPost = new HttpPost(URL);

            // 第二步：转换POST表单Map并放入请求体
            List<NameValuePair> list = new ArrayList<NameValuePair>();

            //TODO:将参数添加到这儿
            list.add(new BasicNameValuePair("groupcode", "0001"));

            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
                httpPost.setEntity(entity);
            }

            // 第三步：发送http post请求，并得到相应结果
            DefaultHttpClient httpclient = HttpUtil.getHttpClient();

            synchronized (httpclient) {
                HttpResponse response = httpclient.execute(httpPost);

                if (response != null) {
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        result = EntityUtils.toString(resEntity, "UTF-8");
                    }
                } else {
                    HashMap<String, Object> rtMap = new HashMap<String, Object>();
                    rtMap.put("retflag", 1);
                    rtMap.put("resMsg", "信息：你要的数据没有得到");
                    HashMap<String, Object> rMap = new HashMap<String, Object>();

                    rMap.put("result", rtMap);
                    rMap.put("res", 0);
                    rMap.put("resMsg", "信息：你要的数据没有得到");
                    result = map2json(rMap);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            HashMap<String, Object> rtMap = new HashMap<String, Object>();
            rtMap.put("retflag", 1);
            rtMap.put("resMsg", "信息：" + e.getMessage());
            HashMap<String, Object> rMap = new HashMap<String, Object>();

            rMap.put("result", rtMap);
            rMap.put("res", 0);
            rMap.put("resMsg", "信息：" + e.getMessage());
            result = map2json(rMap);
        }
        return result;
    }

}
